package com.iot.gateway.tsl.service.impl;

import com.iot.gateway.tsl.qo.DeviceQo;
import com.iot.gateway.tsl.qo.ProductQo;
import com.iot.gateway.tsl.service.*;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class TslModelServiceImpl implements TslModelService {

    private final TslDeviceService deviceService;
    private final TslProductService productService;
    private final TslDeviceSpecService specService;
    private final TslPropertyService propertyService;
    private final TslEventService eventService;
    private final TslServiceService commandService;

    public TslModelServiceImpl(
            TslDeviceService deviceService,
            TslProductService productService,
            TslDeviceSpecService specService,
            TslPropertyService propertyService,
            TslEventService eventService,
            TslServiceService commandService) {
        this.deviceService    = deviceService;
        this.productService   = productService;
        this.specService      = specService;
        this.propertyService  = propertyService;
        this.eventService     = eventService;
        this.commandService   = commandService;
    }

    @Override
    public Map<String, Object> getModel(String deviceId) {
        //从 device 表获取所属 productKey
        DeviceQo device = deviceService.getDevice(deviceId);
        if (device == null) {
            throw new ResponseStatusException(
                    HttpStatus.NOT_FOUND,
                    "设备不存在: " + deviceId
            );
        }

        //根据 productKey 查询 Profile(version)
        ProductQo profile = productService.getProduct(device.getProductKey());
        if (profile == null) {
            throw new ResponseStatusException(
                    HttpStatus.NOT_FOUND,
                    "产品 Profile 不存在: " + device.getProductKey()
            );
        }

        Map<String, Object> model = new LinkedHashMap<>();
        Map<String, Object> profileMap = new LinkedHashMap<>();
        profileMap.put("productKey", profile.getProductKey());
        profileMap.put("version", profile.getVersion());
        model.put("profile", profileMap);
        model.put("specs", specService.getSpecs(deviceId));
        model.put("properties", propertyService.getProperties(deviceId));
        model.put("events", eventService.getEvents(deviceId));
        model.put("commands", commandService.getServices(deviceId));

        return model;
    }
}
